/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.test.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.thinkgem.jeesite.common.utils.GCJ02ToWGS84;
import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.test.entity.LocateInfo;
import com.thinkgem.jeesite.modules.test.entity.VehicleEHS3Result;

import redis.clients.jedis.Jedis;

/**
 * YDCXService
 * @author ThinkGem
 * @version 2013-10-17
 */
@Service
@Transactional(readOnly = true)
public class JedisService {
	
	private Jedis jedis;
	
	public List<VehicleEHS3Result> queryEHS3VehicleInfoByTerminalCode(String terminalCodes) throws Exception  {
		List<VehicleEHS3Result> list = new ArrayList<VehicleEHS3Result>();
		//判断设备号是否为空
		if(StringUtils.isBlank(terminalCodes)){
			throw new Exception("请输入设备号!");
		}
		
		try{
			//解析设备号字符串
			String[] terminalCodeArray = terminalCodes.split(",");
			if(terminalCodeArray != null && terminalCodeArray.length > 0){
				
				//redis初始化
				jedis = JedisUtils.getResource(); 
				jedis.select(2);
				//获取所有的vin
				Set<String> sets = jedis.keys("*");
				for(int index=0; index<terminalCodeArray.length; index++){
					String terminalCode = StringUtils.EMPTY;
					if(sets != null && sets.size() > 0){
						for(String vin : sets){
							if(terminalCodeArray[index].equals(vin)){
								terminalCode = vin;
							}
						}
					}
					
					Set<String> keySet = jedis.hkeys(terminalCode);
					
					//车辆时间戳列表
					List<String> lastRefreshTimeList = new ArrayList<String>();
					
					if(keySet != null && keySet.size() > 0){
						for(String lastRefreshTime : keySet){
							lastRefreshTimeList.add(lastRefreshTime);
						}
						if(lastRefreshTimeList != null && lastRefreshTimeList.size() > 0){
							Collections.sort(lastRefreshTimeList);
						}
					}
					
					if(lastRefreshTimeList != null && lastRefreshTimeList.size() > 0){
						for(int i=lastRefreshTimeList.size()-1; i>=0; i--){
							String finalTime = lastRefreshTimeList.get(i);
							String value = jedis.hget(terminalCodeArray[index], finalTime);
							if(StringUtils.isBlank(value) || value.equals("{}")){
								continue;
							}else{
								VehicleEHS3Result vehicle = this.parseEHS3RealJson2Object(terminalCodeArray[index], finalTime.toString(), value);
								if(vehicle == null){
									continue;
								}else{
									list.add(vehicle);
									//向缓存表中增加数据
									//this.updateVinCache(terminalCodeArray[index], finalTime.toString(), value);
									break;
								}
							}
						}
					}
				}
			}
		
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			jedis.close();
		}
		return list;
	}
	
	public List<VehicleEHS3Result> queryEHS3VehicleTrackInfoByTerminalCode(String terminalCode, String startTime, String endTime) throws Exception{
		List<VehicleEHS3Result> list = new ArrayList<VehicleEHS3Result>();
		//判断设备号是否为空
		if(StringUtils.isBlank(terminalCode)){
			throw new Exception("请输入设备号!");
		}
		//判断开始时间是否为空
		if(StringUtils.isBlank(startTime)){
			throw new Exception("请输入开始时间!");
		}
		//判断结束时间是否为空
		if(StringUtils.isBlank(endTime)){
			throw new Exception("请输入结束时间!");
		}
		
		SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long startTimeLong = sdfStart.parse(startTime).getTime();
		String startTimeLongStr = startTimeLong.toString() + "000000";
		Long startTimeLongNew = Long.parseLong(startTimeLongStr);
		
		SimpleDateFormat sdfEnd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long endTimeLong = sdfEnd.parse(endTime).getTime();
		String endTimeLongStr = endTimeLong.toString() + "000000";
		Long endTimeLongNew = Long.parseLong(endTimeLongStr);
		
		try{
			//redis初始化
			jedis = JedisUtils.getResource();
			//获取redis中所有的所有的key值
			jedis.select(2);
			Set<String> sets = jedis.keys("*");
			if(sets.size() > 0){
				for(String str : sets){
					if(terminalCode.equals(str)){
						Set<String> vehicleSets = jedis.hkeys(terminalCode);
						if(vehicleSets.size() > 0){
							for(String vts : vehicleSets){
								Long time1 = Long.parseLong(vts.substring(0,19));
								Long time2 = Long.parseLong(vts.substring(19,38));
								String value = jedis.hget(terminalCode, vts);
								if(time1 > startTimeLongNew && time1 < endTimeLongNew){
									VehicleEHS3Result vehicle = this.parseEHS3RealJson2Object(terminalCode, value);
									if(vehicle != null){
										list.add(vehicle);
									}
								}else if(time2 > startTimeLongNew && time2 < endTimeLongNew){
									VehicleEHS3Result vehicle = this.parseEHS3RealJson2Object(terminalCode, value);
									if(vehicle != null){
										list.add(vehicle);
									}
								}
							}
						}
					}
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			//释放资源
			jedis.close();
		}
		
		return list;
	}
	
	/**
	 * 根据设备号更新缓存表
	 * @param terminalCode
	 * @return
	 * @throws Exception
	 */
	public void updateVinCache(String terminalCode, String finalTime, String value) throws Exception{
		if(StringUtils.isBlank(terminalCode)){
			return;
		}
		
		//去掉多余的u
		if(StringUtils.isNotBlank(value)){
			value = value.replace("u", StringUtils.EMPTY);
		}
		
		//redis初始化
		jedis.select(0);
		
		//首先判断设备号在缓存中是否存在
		boolean valueIsExist = jedis.hexists("tm30_status_ehs3_vin_value_cache", terminalCode);
		boolean stampIsExist = jedis.hexists("tm30_status_ehs3_vin_value_timestamp_cache", finalTime);
		if(valueIsExist){
			//删除实时信息缓存
			jedis.hdel("tm30_status_ehs3_vin_value_cache", terminalCode);
			//删除实时时间戳缓存
			jedis.hdel("tm30_status_ehs3_vin_timestamp_cache", terminalCode);
			//新增实时信息
			jedis.hset("tm30_status_ehs3_vin_value_cache", terminalCode, value);
	 		//新增时间戳缓存
			jedis.hset("tm30_status_ehs3_vin_timestamp_cache", terminalCode, finalTime);
		}else{
			//新增实时信息
			jedis.hset("tm30_status_ehs3_vin_value_cache", terminalCode, value);
	 		//新增时间戳缓存
			jedis.hset("tm30_status_ehs3_vin_timestamp_cache", terminalCode, finalTime);
		}
		//释放资源
		JedisUtils.returnResource(jedis);
	}
	
	/**
	 * 获取ehs3当前设备的实时信息
	 * @param terminalCode
	 * @param lastRefreshTime
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public VehicleEHS3Result parseEHS3RealJson2Object(String terminalCode, String lastRefreshTime, String jsonStr) throws Exception{
		VehicleEHS3Result vehicle = new VehicleEHS3Result();
		//判断value值是否为空
		if(StringUtils.isBlank(terminalCode)){
			throw new Exception("没有终端号!");
		}
		
		if(StringUtils.isBlank(jsonStr) || jsonStr.equals("{}")){
			return null;
		}
		
		//去掉多余的u
		String jsonResult = jsonStr.replace("u", StringUtils.EMPTY);
		//拼装数据对象
		if(StringUtils.isNotBlank(jsonStr)){
			//将字符串转换为json对象
			JSONObject jsonVehicle = JSONObject.parseObject(jsonResult);
			vehicle.setTerminalCode(terminalCode);
			
			try{
				//获取eventCode
				String eventCode = jsonVehicle.getString("event_code");
				vehicle.setEventCode(eventCode);
				
				String lgt = StringUtils.EMPTY;
				String lat = StringUtils.EMPTY;
				
				JSONObject jsonVehicleData = (JSONObject)jsonVehicle.get("data");
				if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS002"))){
					lgt = JSONObject.parseObject(jsonVehicleData.getString("GPS002")).getString("val");
					vehicle.setLgt(Double.parseDouble(lgt));
				}else{
					return null;
				}
				if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS003"))){
					lat = JSONObject.parseObject(jsonVehicleData.getString("GPS003")).getString("val");
					vehicle.setLat(Double.parseDouble(lat));
				}else{
					return null;
				}

				//经纬度由GCLJ02转换为WGS84体系
				LocateInfo locateInfo = GCJ02ToWGS84.gcj02ToWgs84(Double.parseDouble(lat), Double.parseDouble(lgt));
				vehicle.setLat(locateInfo.getLatitude());
				vehicle.setLgt(locateInfo.getLongitude());
				
				if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS006"))){
					String angle = JSONObject.parseObject(jsonVehicleData.getString("GPS006")).getString("val");
					vehicle.setAngle(Double.parseDouble(angle));
				}else{
					vehicle.setAngle(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicleData.getString("V019"))){
					String speed = JSONObject.parseObject(jsonVehicleData.getString("V019")).getString("val");
					vehicle.setSpeed(Double.parseDouble(speed));
				}else{
					vehicle.setSpeed(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicleData.getString("V015"))){
					String totalKm = JSONObject.parseObject(jsonVehicleData.getString("V015")).getString("val");
					vehicle.setTotalKm(Double.parseDouble(totalKm));
				}else{
					vehicle.setTotalKm(Double.parseDouble("0"));
				}
				if(StringUtils.isNotBlank(jsonVehicleData.getString("V133"))){
					String enableKm = JSONObject.parseObject(jsonVehicleData.getString("V133")).getString("val");
					vehicle.setEnableKm(enableKm);
				}else{
					return null;
				}
				if(StringUtils.isNotBlank(jsonVehicleData.getString("E010"))){
					String powerPer = JSONObject.parseObject(jsonVehicleData.getString("E010")).getString("val");
					vehicle.setSoc(Integer.parseInt(powerPer));
				}else{
					return null;
				}
				
				vehicle.setLastRefreshTime(lastRefreshTime.substring(0, 13));
				
			}catch(Exception ex){
				throw new Exception(ex.getMessage());
			}
		}
		return vehicle;
	}
	
	/**
	 * 获取ehs3当前设备的实时信息(新)
	 * @param terminalCode
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public VehicleEHS3Result parseEHS3RealJson2Object(String terminalCode, String jsonStr) throws Exception{
		VehicleEHS3Result vehicle = new VehicleEHS3Result();
		//判断value值是否为空
		if(StringUtils.isBlank(terminalCode)){
			throw new Exception("没有终端号!");
		}
		
		if(StringUtils.isBlank(jsonStr) || jsonStr.equals("{}")){
			return null;
		}
		
		//去掉多余的u
		String jsonResult = jsonStr.replace("u", StringUtils.EMPTY);
		
		if(StringUtils.isNotBlank(jsonStr)){
			//将字符串转换为json对象
			JSONObject jsonVehicle = JSONObject.parseObject(jsonResult);
			vehicle.setTerminalCode(terminalCode);
			
			try{
				//获取eventCode
				String eventCode = jsonVehicle.getString("event_code");
				
				if(eventCode.equals("DRIVETIMER") || eventCode.equals("TURNSTART") || eventCode.equals("TURNEND") || eventCode.equals("POSITIONANDSPEED")){
					vehicle.setEventCode(eventCode);
					
					//设备上传时间
					String lastRefreshTime = jsonVehicle.getString("pkg_ts");
					vehicle.setLastRefreshTime(lastRefreshTime);
					
					String lgt = StringUtils.EMPTY;
					String lat = StringUtils.EMPTY;
					
					JSONObject jsonVehicleData = (JSONObject)jsonVehicle.get("data");
					if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS002"))){
						lgt = JSONObject.parseObject(jsonVehicleData.getString("GPS002")).getString("val");
						vehicle.setLgt(Double.parseDouble(lgt));
					}else{
						return null;
					}
					if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS003"))){
						lat = JSONObject.parseObject(jsonVehicleData.getString("GPS003")).getString("val");
						vehicle.setLat(Double.parseDouble(lat));
					}else{
						return null;
					}
	
					//经纬度由GCLJ02转换为WGS84体系
					LocateInfo locateInfo = GCJ02ToWGS84.gcj02ToWgs84(Double.parseDouble(lat), Double.parseDouble(lgt));
					vehicle.setLat(locateInfo.getLatitude());
					vehicle.setLgt(locateInfo.getLongitude());
					
					if(StringUtils.isNotBlank(jsonVehicleData.getString("GPS006"))){
						String angle = JSONObject.parseObject(jsonVehicleData.getString("GPS006")).getString("val");
						vehicle.setAngle(Double.parseDouble(angle));
					}else{
						vehicle.setAngle(Double.parseDouble("0"));
					}
					if(StringUtils.isNotBlank(jsonVehicleData.getString("V019"))){
						String speed = JSONObject.parseObject(jsonVehicleData.getString("V019")).getString("val");
						vehicle.setSpeed(Double.parseDouble(speed));
					}else{
						vehicle.setSpeed(Double.parseDouble("0"));
					}
					if(StringUtils.isNotBlank(jsonVehicleData.getString("V015"))){
						String totalKm = JSONObject.parseObject(jsonVehicleData.getString("V015")).getString("val");
						vehicle.setTotalKm(Double.parseDouble(totalKm));
					}else{
						vehicle.setTotalKm(Double.parseDouble("0"));
					}
					if(StringUtils.isNotBlank(jsonVehicleData.getString("V133"))){
						String enableKm = JSONObject.parseObject(jsonVehicleData.getString("V133")).getString("val");
						vehicle.setEnableKm(enableKm);
					}else{
						return null;
					}
					if(StringUtils.isNotBlank(jsonVehicleData.getString("E010"))){
						String powerPer = JSONObject.parseObject(jsonVehicleData.getString("E010")).getString("val");
						vehicle.setSoc(Integer.parseInt(powerPer));
					}else{
						return null;
					}
			}else{
				return null;
			}
				
			}catch(Exception ex){
				throw new Exception(ex.getMessage());
			}
		}
		return vehicle;
	}
}
